//
//  MiTuGift.swift
//  MT
//
//  Created by M on 2019/12/15.
//  Copyright © 2019 张强. All rights reserved.
//

import UIKit

/// 网络请求

import RxSwift
import RxDataSources
import Moya
import Result
/// MT 分类
import MTCategory

/// 其他
import Kingfisher

// MARK: ------------------ 糜荼弹出 View ----------------------
class MiTuGiftView: BaseAlertView {
    
    /// 单个礼物 Cell 的高度
    static var itemHeight: CGFloat {
        return 91.0
    }
    static var collectionViewHeight: CGFloat {
        return itemHeight * 2
    }
    /// 礼物 View 总高度
    static var viewHeight: CGFloat {
        return 290
    }
    /// 是否是好友关系
    private var isFriend: Bool?
    
    /// 礼物模型
    var models: [MiTuGiftModel]? {
        didSet {
            self.collectionView.reloadData()
        }
    }
    
    /// IM username
    private var imUserName: String?
    
    /// MTProvider
    fileprivate lazy var provider: MTProvider<MiTuGiftApi> = {
        return MTProvider<MiTuGiftApi>(plugins: [])
    }()
    private let disposedBag = DisposeBag()
    
    private init() {
        super.init(height: MiTuGiftView.viewHeight)
        initializeUI()
        request()
        
        //UserDefaults.MTUserCenter.money.storedInt
        MTClubTool.config(provider: clubProvider, complete: { [weak self] (model) in
            guard let weakSelf = self else { return }
            guard let ticketAmount = model?.result?.ticketAmount else { return }
            DispatchQueue.main.async {
                weakSelf.balanceButton.setTitle("余额 \(ticketAmount)", for: .normal)
                if let imageView = weakSelf.balanceButton.imageView { weakSelf.balanceButton.titleEdgeInsets = UIEdgeInsets(top: 0, left: -imageView.frame.width, bottom: 0, right: imageView.frame.width) }
                if let titleLabel = weakSelf.balanceButton.titleLabel { weakSelf.balanceButton.imageEdgeInsets = UIEdgeInsets(top: 0, left: titleLabel.frame.width + 2, bottom: 0, right: -titleLabel.frame.width) }
            }
        }) { [weak self] (error) in
            
        }
        
    }
    
    override func didMoveToWindow() {
        super.didMoveToWindow()
        if let isF = isFriend, isF {
            tipContentLabel.isHidden = true
            sayHiButton.isHidden = true
            giftNumberLayerView.isHidden = false
            sendGiftButton.isHidden = false
            giftNumberButton.isHidden = false
        } else {
            giftNumberButton.isHidden = true
            tipContentLabel.isHidden = false
            sayHiButton.isHidden = false
            giftNumberLayerView.isHidden = true
            sendGiftButton.isHidden = true
        }
    }
    
    /// 点击送礼物回调
    public typealias SelectedGiftCallBack = (_ model: MiTuGiftModel, _ count: Int) -> Swift.Void
    /// 点击充值余额
    public typealias DidClickRechargeCallBack = () -> Swift.Void

    private var didClickRechargeCallBack: DidClickRechargeCallBack?
    private var selectedGiftCallBack: SelectedGiftCallBack?
    private var didClickSayHiCallBack: SelectedGiftCallBack?
    private var didDismissCallBack: DidClickRechargeCallBack?
    private let clubProvider: MTProvider = MTProvider<MTClubApi>()
    
    convenience init(didClickRechargeCallBack: DidClickRechargeCallBack? = nil, selectedGiftCallBack: SelectedGiftCallBack? = nil) {
        self.init()
        self.didClickRechargeCallBack = didClickRechargeCallBack
        self.selectedGiftCallBack = selectedGiftCallBack
    }
    
    /// 送礼物
    /// - Parameters:
    ///   - isFriend: 是否是好友关系
    ///   - imUserName: 礼物接受者的 im 账号
    ///   - didClickRechargeCallBack: didClickRechargeCallBack description
    ///   - selectedGiftCallBack: selectedGiftCallBack description
    convenience init(isFriend: Bool, imUserName: String, didClickRechargeCallBack: DidClickRechargeCallBack? = nil, selectedGiftCallBack: SelectedGiftCallBack? = nil, didClickSayHiCallBack: @escaping SelectedGiftCallBack, didDismissCallBack: @escaping DidClickRechargeCallBack) {
        self.init()
        self.imUserName = imUserName
        self.isFriend = isFriend
        self.didClickRechargeCallBack = didClickRechargeCallBack
        self.selectedGiftCallBack = selectedGiftCallBack
        self.didClickSayHiCallBack = didClickSayHiCallBack
        self.didDismissCallBack = didDismissCallBack
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /// collection view
    lazy var collectionView: UICollectionView = {
        /// 设置大小
        let inset: CGFloat = 16.0
        let itemWidth = (ScreenWidth - inset * 2) / 4
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.itemSize = CGSize(width: itemWidth, height: MiTuGiftView.itemHeight)
        flowLayout.minimumLineSpacing = 0
        flowLayout.minimumInteritemSpacing = 0
        flowLayout.scrollDirection = .horizontal
        let cv = UICollectionView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: MiTuGiftView.collectionViewHeight), collectionViewLayout: flowLayout)
        cv.backgroundColor = UIColor.common.x161616
        cv.contentInset = UIEdgeInsets(top: 0, left: inset, bottom: 0, right: inset)
        cv.showsVerticalScrollIndicator = false
        cv.delegate = self
        cv.dataSource = self
//        cv.isPagingEnabled = true
        cv.showsHorizontalScrollIndicator = false
        /// 注册 Cell
        cv.register(MiTuGiftCell.self, forCellWithReuseIdentifier: String(describing: MiTuGiftCell.self))
        return cv
    }()
    
    /// 余额按钮
    lazy var balanceButton: UIButton = {
        let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 200, height: 20))
        btn.setImage(UIImage(named: "icon_arrow_right"), for: .normal)
        btn.setTitle("余额 0", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = PingFangSCMediumFont(12)
        btn.adjustsImageWhenHighlighted = false
        btn.contentHorizontalAlignment = .left
        if let imageView = btn.imageView {
            btn.titleEdgeInsets = UIEdgeInsets(top: 0, left: -imageView.frame.width, bottom: 0, right: imageView.frame.width)
        }
        if let titleLabel = btn.titleLabel {
            btn.imageEdgeInsets = UIEdgeInsets(top: 0, left: titleLabel.frame.width + 5, bottom: 0, right: -titleLabel.frame.width)
        }
        btn.addTarget(self, action: #selector(mituGiftView(didClickBalanceButton:)), for: .touchUpInside)
        return btn
    }()
    
    /// 用礼物打个招呼按钮
    lazy var sayHiButton: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("用礼物打个招呼", for: .normal)
        btn.addTarget(self, action: #selector(mituGiftView(didClickSayHiButton:)), for: .touchUpInside)
        btn.setTitleColor(UIColor.text.x1d1a1a, for: .normal)
        btn.titleLabel?.font = PingFangSCSemiboldFont(12)
        btn.layer.cornerRadius = 16
        btn.backgroundColor = UIColor(hex: 0xffc000)
        btn.layer.masksToBounds = true
        return btn
    }()
    /// 非好友状态下, 提示信息
    lazy var tipContentLabel: UILabel = {
        let l = UILabel()
        l.font = PingFangSCRegularFont(10)
        l.textColor = UIColor(hex: 0xffc000)
        l.text = "需要赠送礼物才可以添加好友，如被拒绝，礼物会原路返还用户"
        return l
    }()
//
//    /// 非好友状态横线View
//    lazy var lineView: UIView = {
//        let v = UIView()
//        v.backgroundColor = UIColor.text.x9b9b9b
//        return v
//    }()
//
//    /// 非好友顶部提示文字 = 好友申请
//    lazy var topTipContentLabel: UILabel = {
//        let l = UILabel()
//        l.font = PingFangSCSemiboldFont(16)
//        l.textColor = UIColor.white
//        l.text = "好友申请"
//        return l
//    }()
    
    /// 数量按钮底 View
    lazy var giftNumberLayerView: UIView = {
        let v = UIView()
        v.layer.cornerRadius = 10
        v.layer.borderWidth = 1
        v.layer.borderColor = UIColor.white.cgColor
        return v
    }()
    /// 数量按钮
    lazy var giftNumberButton: UIButton = {
        let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 70, height: 30))
        btn.setImage(UIImage(named: "icon_arrow_up")?.resize(to: CGSize(width: 15, height: 15)), for: .normal)
        btn.setTitle("+1", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = PingFangSCRegularFont(14)
        btn.adjustsImageWhenHighlighted = false
        if let imageView = btn.imageView {
            btn.titleEdgeInsets = UIEdgeInsets(top: 0, left: -imageView.frame.width, bottom: 0, right: imageView.frame.width)
        }
        if let titleLabel = btn.titleLabel {
            btn.imageEdgeInsets = UIEdgeInsets(top: 2, left: titleLabel.frame.width + 8, bottom: 0, right: -titleLabel.frame.width)
        }
        btn.addTarget(self, action: #selector(mituGiftView(didClickGiftNumberButton:)), for: .touchUpInside)
        return btn
    }()
    
    /// 是否隐藏 数量 View
    private var isGiftCountTableViewHidden: Bool = true
    /// 送礼数量
    private var giftCount: Int = 1
    
    /// 送礼物按钮
    lazy var sendGiftButton: UIButton = {
        let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 60, height: 30))
        btn.backgroundColor = UIColor.theme.main
        btn.setTitle("发送", for: .normal)
        btn.setTitleColor(UIColor.text.x1d1a1a, for: .normal)
        btn.titleLabel?.font = PingFangSCRegularFont(14)
        btn.adjustsImageWhenHighlighted = false
        btn.clipRectCorner(direction: [.topRight, .bottomRight], cornerRadius: 10)
        btn.addTarget(self, action: #selector(mituGiftView(didClickSendGiftButton:)), for: .touchUpInside)
        return btn
    }()
    /// 数量 TableView
    lazy var countTableView: MTGiftCountTableView = {
        let tv = MTGiftCountTableView(frame: CGRect(x: 0, y: 0, width: 130, height: MTGiftCountTableView.tableViewHeight))
        tv.countDelegate = self
        tv.alpha = 0
        return tv
    }()
    
    /// TableView 三角形
    lazy var icon_triangleImage: UIImageView = {
        let imgView = UIImageView()
        imgView.image = UIImage(named: "icon_triangle")
        imgView.contentMode = .scaleAspectFill
        imgView.alpha = 0
        return imgView
    }()
    
    override func dismiss(animated: Bool = true, completion: ((Bool) -> Void)? = nil) {
        didDismissCallBack?()
        super.dismiss(animated: animated, completion: completion)
    }
    
}

// MARK: ------------------ UI 初始化 ----------------------
extension MiTuGiftView {
    
    private func initializeUI() {
        backgroundCoverBackgroundColor = .clear
        title = "礼物"
        addSubview(tipContentLabel)
        
        addSubview(collectionView)
        addSubview(balanceButton)
        addSubview(giftNumberLayerView)
        addSubview(giftNumberButton)
        addSubview(sendGiftButton)
        addSubview(countTableView)
        addSubview(icon_triangleImage)
        addSubview(sayHiButton)
        
        collectionView.snp.makeConstraints { (make) in
            make.top.equalTo(titleView.snp.bottom).offset(16)
            make.left.right.equalTo(self)
            make.height.equalTo(MiTuGiftView.collectionViewHeight)
        }
        
        balanceButton.snp.makeConstraints { (make) in
            make.left.equalTo(self).offset(16)
            make.width.equalTo(200)
            make.height.equalTo(20)
            make.bottom.equalTo(self).offset(-ScreenBottomExtraOffset - 10)
        }
        
        sendGiftButton.snp.makeConstraints { (make) in
            make.right.equalTo(self).offset(-16)
            make.centerY.equalTo(balanceButton)
            make.width.equalTo(60)
            make.height.equalTo(30)
        }
        
        sayHiButton.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.centerY.equalTo(giftNumberLayerView)
            make.width.equalTo(144)
            make.height.equalTo(32)
        }
        
        tipContentLabel.snp.makeConstraints { (make) in
            make.centerY.equalTo(titleView)
            make.left.equalTo(titleView.snp.right).offset(5)
            make.right.equalTo(dismissButton.snp.left).offset(-5)
        }
        
        giftNumberLayerView.snp.makeConstraints { (make) in
            make.right.equalTo(sendGiftButton.snp.left).offset(10)
            make.centerY.equalTo(sendGiftButton)
            make.width.equalTo(80)
            make.height.equalTo(30)
        }
        
        giftNumberButton.snp.makeConstraints { (make) in
            make.right.equalTo(sendGiftButton.snp.left)
            make.centerY.equalTo(sendGiftButton)
            make.width.equalTo(70)
            make.height.equalTo(30)
        }
        
        countTableView.snp.makeConstraints { (make) in
            make.right.equalTo(sendGiftButton)
            make.bottom.equalTo(sendGiftButton.snp.top).offset(-12)
            make.height.equalTo(MTGiftCountTableView.tableViewHeight)
            make.width.equalTo(130)
        }
        
        icon_triangleImage.snp.makeConstraints { (make) in
            make.top.equalTo(countTableView.snp.bottom)
            make.centerX.equalTo(countTableView)
        }
        
    }
    
}

// MARK: ------------------ 数据请求 ----------------------
extension MiTuGiftView {
    
    /// 请求礼物列表
    public func request() {
        provider.rx.requestResult(.list).subscribe(onNext: { (result: Result<MiTuGiftResponseModel, AnyError>, isCache: Bool) in
            self.models = result.result.value?.result
        }).disposed(by: disposedBag)
    }
    
}

// MARK: ------------------ 事件方法 ----------------------
@objc
extension MiTuGiftView {
    
    /// 非好友关系系下, 用礼物打招呼按钮
    private func mituGiftView(didClickSayHiButton sender: UIButton) {
        guard let models = models else { return }
        var model: MiTuGiftModel?
        for m in models {
            if m.isSelected {
                model = m
                break
            }
        }
        guard let selectedModel = model else {
            /// 是否需要提示 ？
            MBProgressHUD_JChat.show(text: "请选择礼物", view: UIApplication.shared.keyWindow!)
            return
        }
        self.didClickSayHiCallBack?(selectedModel, 1)
        self.dismiss(animated: false, completion: nil)
    }
    
    /// 点击余额按钮
    private func mituGiftView(didClickBalanceButton sender: UIButton) {
        
    }
    
    /// 点击礼物数量按钮
    private func mituGiftView(didClickGiftNumberButton sender: UIButton) {
        isGiftCountTableViewHidden = !isGiftCountTableViewHidden
        isGiftCountTableViewHidden ? dismissCountTableView() : presentCountTableView()
    }
    
    /// 点击发送按钮
    private func mituGiftView(didClickSendGiftButton sender: UIButton) {
        guard let models = models else { return }
        var model: MiTuGiftModel?
        for m in models {
            if m.isSelected {
                model = m
                break
            }
        }
        guard let selectedModel = model else {
            /// 是否需要提示 ？
            return
        }
        if let c = UIApplication.shared.keyWindow?.rootViewController {
            MTClubTool.config(provider: clubProvider, complete: { [weak self] (model) in
                guard let weakSelf = self else { return }
                let amount = (selectedModel.price ?? 0) * weakSelf.giftCount
                guard let ticketAmount = model?.result?.ticketAmount else { return }
                if model?.code == 200, amount > ticketAmount {
                    UIAlertController.rx.show(in: c, title: "余额不足", message: "此次将花费\(amount)钻石", buttons: [.cancel("取消"), .default("去充值")]).subscribe(onSuccess: { index in
                        /// 去充值的引导
                        if index == 1 {
                            if UserDefaults.AppValidate.isValidate.storedBool == false {
                                if let callback = weakSelf.didClickRechargeCallBack {
                                    callback()
                                    weakSelf.dismiss(animated: false, completion: nil)
                                }
                            } else {
                                if let callback = weakSelf.didClickRechargeCallBack {
                                    callback()
                                    weakSelf.dismiss(animated: false, completion: nil)
                                }
                            }
                        }
                    })
                    .disposed(by: globalDisposedBag)
                    return
                } else {
                    if let giftId = selectedModel.id {
                        weakSelf.sendGift(giftCount: weakSelf.giftCount, giftId: giftId)
                    }
                }
            }) { [weak self] (error) in
                guard let weakSelf = self else { return }
                MBProgressHUD_JChat.show(text: "网络异常", view: c.view)
                MBProgressHUD_JChat.dismiss(c.view)
                return
            }
        }
    }
    
    private func sendGift(giftCount: Int, giftId: Int) {
        guard let userName = self.imUserName else { return }
        let requestParam: [String : Any] = ["count": giftCount,
                                            "giftId": giftId,
                                            "message": "",
                                            "userName": userName]
        
        provider.originRequest(.sendGift(requestParam), callbackQueue: .main, progress: nil) { [weak self] (result, _) in
            guard let weakSelf = self else { return }
            switch result {
            case let .success(response):
                if let datas = try? response.mapJSON() as? [String: Any], let code = datas["code"] as? Int {
                    
                    if code == 200 {
                        if let result = datas["result"] as? [String: Any] {
                            UserCenter.default.set(with: result)
                        }
                        AlertManager.presentAlertView(message: "送礼成功") { [weak self] in
                            guard let weakself = self else { return }
                            weakself.dismiss()
                        }
                    } else if code == 600 {
                        // 600 余额不做
                        weakSelf.presentFailAlert()
                    } else {
                        AlertManager.presentAlertView(message: "送礼失败")
                    }
                } else {
                    AlertManager.presentAlertView(message: "送礼失败")
                }
                break
                
            case .failure(_):
                AlertManager.presentAlertView(message: "送礼失败")
                break
            }
        }
    }
    
    private func presentFailAlert() {
        if UserDefaults.AppValidate.isValidate.storedBool == false {
            if let callback = self.didClickRechargeCallBack {
                callback()
                self.dismiss(animated: false, completion: nil)
            }
            
        } else {
            if let callback = self.didClickRechargeCallBack {
                callback()
                self.dismiss(animated: false, completion: nil)
            }
        }
    
//        let c = UIAlertController(title: "提示", message: "请添加微信号觅颜 me move进行充值", preferredStyle: .alert)
//        let a1 = UIAlertAction(title: "复制微信号", style: .default) { (_) in
//            UIPasteboard.general.string = "觅颜 me move"
//            AlertManager.presentAlertView(message: "复制成功")
//        }
//        let c1 = UIAlertAction(title: "取消", style: .cancel, handler: nil)
//        c.addAction(a1)
//        c.addAction(c1)
//        UIApplication.shared.keyWindow?.rootViewController?.present(c, animated: true, completion: nil)
    }
    
}

// MARK: ------------------------------------ 数量选择 ----------------------------------------
extension MiTuGiftView {
    
    private func presentCountTableView() {
        UIView.animate(withDuration: 0.25, animations: {
            self.countTableView.alpha = 1
            self.icon_triangleImage.alpha = 1
        }) { (_) in
            
        }
    }
    
    private func dismissCountTableView() {
        //didDismissCallBack?()
        UIView.animate(withDuration: 0.25, animations: {
            self.countTableView.alpha = 0
            self.icon_triangleImage.alpha = 0
        }) { (_) in
            
        }
    }
    
}

// MARK: ------------------ 所有代理 ----------------------
// MARK: ------------------ UICollectionViewDelegate ----------------------
extension MiTuGiftView: UICollectionViewDelegate {
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        guard let models = models else { return }
        for i in 0..<models.count {
            models[i].isSelected = i == indexPath.item
        }
        collectionView.reloadData()
    }
    
}

// MARK: ------------------ UICollectionViewDataSource ----------------------
extension MiTuGiftView: UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return models?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: MiTuGiftCell.self), for: indexPath) as? MiTuGiftCell else {
            return collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: MiTuGiftCell.self), for: indexPath)
        }
        cell.model = self.models?[indexPath.item]
        return cell
    }
    
}

// MARK: ------------------------------------ MTGiftCountTableViewDelegate ----------------------------------------
extension MiTuGiftView: MTGiftCountTableViewDelegate {
    
    func giftCountTableView(_ tableView: MTGiftCountTableView, didSelectCountWithCount count: Int) {
        giftNumberButton.setTitle("+\(count)", for: .normal)
        if let imageView = giftNumberButton.imageView { giftNumberButton.titleEdgeInsets = UIEdgeInsets(top: 0, left: -imageView.frame.width, bottom: 0, right: imageView.frame.width) }
        if let titleLabel = giftNumberButton.titleLabel { giftNumberButton.imageEdgeInsets = UIEdgeInsets(top: 2, left: titleLabel.frame.width + 8, bottom: 0, right: -titleLabel.frame.width) }
        self.giftCount = count
        isGiftCountTableViewHidden = true
        dismissCountTableView()
    }
    
}

// MARK: ------------------ MiTuGiftCell ----------------------
fileprivate class MiTuGiftCell: UICollectionViewCell {
    
    var model: MiTuGiftModel? {
        didSet {
            guard let model = model else { return }
            if let icon = model.icon, let urlString = URL(string: icon) {
                giftIconImgView.kf.setImage(with: urlString)
            }
            giftNameLabel.text = model.name
            if let p = model.price {
                giftPriceLabel.text = "\(p)钻石"
            }
            self.contentView.layer.borderWidth = model.isSelected ? 1 : 0
        }
    }
    
    /// 礼物图标 ImageView
    lazy var giftIconImgView: UIImageView = {
        let imgView = UIImageView()
        imgView.contentMode = .scaleAspectFill
        return imgView
    }()
    
    /// 礼物名称 Label
    lazy var giftNameLabel: UILabel = {
        let label = UILabel()
        label.font = PingFangSCRegularFont(10)
        label.textColor = .white
        label.textAlignment = .center
        return label
    }()
    
    /// 礼物金额 Label
    lazy var giftPriceLabel: UILabel = {
        let label = UILabel()
        label.font = PingFangSCRegularFont(8)
        label.textColor = UIColor.white.withAlphaComponent(0.6)
        label.textAlignment = .center
        return label
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        initializeUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func initializeUI() {
        contentView.layer.borderColor = UIColor.theme.main.cgColor
        contentView.addSubview(giftIconImgView)
        contentView.addSubview(giftNameLabel)
        contentView.addSubview(giftPriceLabel)
        
        giftIconImgView.snp.makeConstraints { (make) in
            make.top.equalTo(contentView).offset(9)
            make.width.height.equalTo(50)
            make.centerX.equalTo(contentView)
        }
        
        giftNameLabel.snp.makeConstraints { (make) in
            make.top.equalTo(giftIconImgView.snp.bottom).offset(4)
            make.left.equalTo(contentView).offset(10)
            make.right.equalTo(contentView).offset(-10)
            make.height.equalTo(14)
        }
        
        giftPriceLabel.snp.makeConstraints { (make) in
            make.top.equalTo(giftNameLabel.snp.bottom)
            make.left.right.equalTo(giftNameLabel)
        }
    }
    
}
